from flask import jsonify
from flask.views import MethodView
from app.models.user import User
from app.forms.user import UserRegisterForm
from app.extensions import db
from ..auth import auth_required
from flask_login import current_user
from ..forms import UserResetPassword, CodeForm, ValidateCodeForm, UserUpdateCompany
from app.helpers import oss_sms, cache
import random


class UserAPI(MethodView):
    decorators = [auth_required]

    def get(self):
        data = current_user.to_dict()
        return jsonify(success=True, data=data)

    def post(self):
        form = UserResetPassword()
        if form.validate_on_submit():
            if not current_user.validate_password(form.password.data):
                return jsonify(success=False, message=[{"password": "密码不正确"}])

            with db.auto_commit():
                current_user.password = form.new_password.data
            return jsonify(success=True, data=current_user.to_dict())

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)


class UsersCompanyAPI(MethodView):
    decorators = [auth_required]

    def post(self):
        form = UserUpdateCompany()
        if form.validate_on_submit():
            with db.auto_commit():
                current_user.cid = form.cid.data
            return jsonify(success=True, data=current_user.to_dict())

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)


# 注册用户
class UsersAPI(MethodView):
    def post(self):
        form = UserRegisterForm()
        model = User()
        if model.save(form):
            return jsonify(success=True, data=model.to_dict())

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)


# 阿里验证码
class SmsAPI(MethodView):
    # 验证验证码
    def patch(self):
        form = ValidateCodeForm()
        if form.validate_on_submit():
            if cache.get(form.tel.data) is None:
                return jsonify(success=False, message='没有此手机验证码，有可能失效')

            if str(cache.get(form.tel.data)) == form.code.data:
                return jsonify(success=True, message='验证码正确')

            return jsonify(success=False, message='验证码不正确')

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)

    # 获取验证码
    def post(self):
        form = CodeForm()
        if form.validate_on_submit():
            code = random.randint(100000, 999999)
            cache.set('{}'.format(form.tel.data), code, 60 * 4)
            return oss_sms(tel=form.tel.data, code=code)

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)
